import type { Layer } from "@/components/imageEditor/types";

// 复用现有组件
import AnimatedBottomSheet from "@/components/imageEditor/AnimatedBottomSheet";
import { LayerManager } from "@/components/imageEditor/SkiaImageEditor";
import StickerEditor from "@/components/imageEditor/StickerEditor";
import TextEditor from "@/components/imageEditor/TextEditor";

// 媒体选择上下文
import { useMediaSelection } from "@/contexts/MediaSelectionContext";

// 自由拼图组件
import { BackgroundEditor } from "@/components/freePuzzle/BackgroundEditor";
import {
  BrushSettings,
  DrawingTool,
} from "@/components/freePuzzle/DrawingTool";
import {
  FrameEditor,
  FrameSettings,
  FrameStyle,
} from "@/components/freePuzzle/FrameEditor";
import FreePuzzleCanvas, {
  FreePuzzleCanvasRef,
} from "@/components/freePuzzle/FreePuzzleCanvas";
import {
  CanvasSize,
  GridLayout,
  LayoutEditor,
} from "@/components/freePuzzle/LayoutEditor";
import {
  MaskEditor,
  MaskSettings,
  MaskStyle,
} from "@/components/freePuzzle/MaskEditor";
import { PhotoEditor } from "@/components/freePuzzle/PhotoEditor";

import goon from "@/assets/svg/goon.svg";
import layers from "@/assets/svg/layers.svg";
import retuen from "@/assets/svg/retuen.svg";
import {
  ScrollableToolbar,
  ToolbarItem,
} from "@/components/ui/ScrollableToolbar";
import { SvgIcon } from "@/components/ui/SvgIcon";
import { Entypo, MaterialIcons } from "@expo/vector-icons";
import { Stack, useRouter } from "expo-router";
import { useCallback, useEffect, useRef, useState } from "react";

import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

// 自由拼图工具栏选项
const FREE_PUZZLE_TABS: ToolbarItem[] = [
  {
    key: "layout",
    label: "布局",
    icon: "grid-view",
  },
  {
    key: "background",
    label: "背景",
    icon: "image",
  },
  {
    key: "photo",
    label: "相册",
    icon: "add-photo-alternate",
  },
  {
    key: "mask",
    label: "蒙版",
    icon: "layers",
  },
  {
    key: "text",
    label: "文字",
    icon: "text-fields",
  },
  {
    key: "sticker",
    label: "贴纸",
    icon: "emoji-emotions",
  },
  {
    key: "draw",
    label: "涂鸦",
    icon: "brush",
  },
  {
    key: "frame",
    label: "相框",
    icon: "crop-original",
  },
];

export default function FreePuzzleScreen() {
  const [tab, setTab] = useState("");
  const [showBottomSheet, setShowBottomSheet] = useState(false);
  const [showLayerManager, setShowLayerManager] = useState(false);
  const [layersList, setLayersList] = useState<Layer[]>([]);

  // 文字相关状态
  const [currentTextData, setCurrentTextData] = useState<any>(null);
  const [currentTextTab, setCurrentTextTab] = useState<string>("font");

  // 贴纸相关状态
  const [currentStickerData, setCurrentStickerData] = useState<any>(null);

  // 新增状态
  const [selectedLayerId, setSelectedLayerId] = useState<string | undefined>();
  const [canvasSize, setCanvasSize] = useState<CanvasSize>({
    key: "1:1",
    label: "正方形",
    aspectRatio: 1,
    width: 400,
    height: 400,
  });
  const [gridLayout, setGridLayout] = useState<GridLayout>({
    key: "none",
    label: "无网格",
    rows: 1,
    cols: 1,
    type: "regular",
  });

  // 容器尺寸状态
  const [containerSize, setContainerSize] = useState({
    width: 400,
    height: 400,
  });

  // 新扩展功能的状态
  const [currentVideoData, setCurrentVideoData] = useState<any>(null);
  const [currentFrameData, setCurrentFrameData] = useState<FrameStyle | null>(
    null
  );
  const [currentFrameSettings, setCurrentFrameSettings] =
    useState<FrameSettings>({
      borderWidth: 8,
      borderColor: "#FFFFFF",
      cornerRadius: 0,
      shadowEnabled: false,
      shadowColor: "#000000",
      shadowOpacity: 0.25,
      shadowOffset: { x: 0, y: 2 },
      shadowRadius: 4,
    });
  const [currentMaskData, setCurrentMaskData] = useState<MaskStyle | null>(
    null
  );
  const [currentMaskSettings, setCurrentMaskSettings] = useState<MaskSettings>({
    opacity: 100,
    feather: 0,
    invert: false,
    blendMode: "normal",
    position: { x: 0, y: 0 },
    scale: 100,
    rotation: 0,
  });

  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { selectedMedia, clearSelection } = useMediaSelection();

  // 画布引用
  const canvasRef = useRef<FreePuzzleCanvasRef>(null);

  // 从画布获取图层数据
  useEffect(() => {
    if (showLayerManager && canvasRef.current) {
      const layers = canvasRef.current.getLayers();
      setLayersList(layers);
    }
  }, [showLayerManager]);

  // 监听媒体选择结果，自动添加到画布
  useEffect(() => {
    if (selectedMedia.length > 0 && canvasRef.current) {
      const photos = selectedMedia
        .filter((m) => m.type === "photo")
        .map((m) => m.url);
      const videos = selectedMedia.filter((m) => m.type === "video");

      // 若存在网格，优先将图片按网格填充
      if (gridLayout.key !== "none" && photos.length > 0) {
        // @ts-ignore 扩展方法：自由拼图画布实现了 fillGridWithImages
        canvasRef.current?.fillGridWithImages?.(photos);
      } else {
        // 无网格则逐个添加，使用 Promise.all 确保所有图片都被处理
        const addImagePromises = photos.map((url, index) => {
          return new Promise<void>((resolve) => {
            // 为每张图片设置固定的网格位置，确保不超出画布边界
            // 使用更保守的尺寸估算，避免超出画布
            const estimatedWidth = Math.min(100, canvasSize.width * 0.3); // 不超过画布宽度的30%
            const estimatedHeight = Math.min(100, canvasSize.height * 0.3); // 不超过画布高度的30%

            // 计算网格布局，根据图片数量确定网格大小
            const gridCols = Math.ceil(Math.sqrt(photos.length)); // 根据图片数量计算列数
            const gridRows = Math.ceil(photos.length / gridCols); // 计算行数

            // 计算每个网格的尺寸
            const gridWidth = Math.min(
              estimatedWidth,
              (canvasSize.width - 40) / gridCols
            ); // 40px总边距
            const gridHeight = Math.min(
              estimatedHeight,
              (canvasSize.height - 40) / gridRows
            );

            // 计算当前图片在网格中的位置
            const gridCol = index % gridCols;
            const gridRow = Math.floor(index / gridCols);

            // 从画布中心开始，每张图片添加不同的偏移
            const centerX = canvasSize.width / 2;
            const centerY = canvasSize.height / 2;

            // 为每张图片添加不同的偏移，避免完全重叠
            const offsetX = ((index % 3) - 1) * 80; // -80, 0, 80
            const offsetY = Math.floor(index / 3) * 80; // 每3张图片换一行

            // 计算最终位置（中心 + 偏移）
            const x = centerX + offsetX - gridWidth / 2;
            const y = centerY + offsetY - gridHeight / 2;

            console.log(`=== 添加第 ${index + 1} 张图片 ===`);
            console.log(`图片URL:`, url);
            console.log(`中心位置: (${centerX}, ${centerY})`);
            console.log(`偏移量: (${offsetX}, ${offsetY})`);
            console.log(`最终位置: (${x}, ${y})`);
            console.log(`图片尺寸: ${gridWidth}x${gridHeight}`);
            console.log(`画布尺寸: ${canvasSize.width}x${canvasSize.height}`);

            canvasRef.current?.addImage({
              source: url,
              x: x,
              y: y,
            });

            // 给每张图片一点延迟，避免同时处理太多图片
            setTimeout(resolve, index * 100);
          });
        });

        // 等待所有图片添加完成
        Promise.all(addImagePromises)
          .then(() => {
            console.log(`=== Promise.all 完成 ===`);
            console.log(`成功添加了 ${photos.length} 张图片`);
            console.log(
              "当前画布图层数量:",
              canvasRef.current?.getLayers().length
            );
          })
          .catch((error) => {
            console.error("添加图片过程中出现错误:", error);
          });
      }

      // 视频仍按原逻辑添加
      videos.forEach((media) => {
        canvasRef.current?.addVideo({
          source: media.url,
          thumbnail: media.url,
          width: media.width || 200,
          height: media.height || 200,
          duration: media.duration,
          x: Math.random() * 100,
          y: Math.random() * 100,
        });
      });
      // 清除选择状态
      clearSelection();
    }
  }, [
    selectedMedia,
    clearSelection,
    gridLayout.key,
    canvasSize.width,
    canvasSize.height,
  ]);

  // 文字编辑器的标签页
  const TEXT_EDITOR_TABS = [
    { key: "fancy", label: "花字" },
    { key: "font", label: "字体" },
    { key: "style", label: "样式" },
    { key: "layout", label: "排版" },
  ];

  // 布局编辑器的标签页
  const LAYOUT_EDITOR_TABS = [
    { key: "size", label: "尺寸" },
    { key: "grid", label: "宫格" },
  ];

  // 背景编辑器的标签页
  const BACKGROUND_EDITOR_TABS = [
    { key: "color", label: "颜色" },
    { key: "image", label: "图片" },
    { key: "gradient", label: "渐变" },
    { key: "pattern", label: "图案" },
  ];

  // 蒙版编辑器的标签页
  const MASK_EDITOR_TABS = [
    { key: "shape", label: "形状" },
    { key: "gradient", label: "渐变" },
  ];

  // 涂鸦工具的标签页
  const DRAW_TOOL_TABS = [
    { key: "brush", label: "画笔" },
    { key: "color", label: "颜色" },
    { key: "settings", label: "设置" },
  ];

  // 相框编辑器的标签页
  const FRAME_EDITOR_TABS = [
    { key: "preset", label: "预设" },
    { key: "custom", label: "自定义" },
  ];

  // 当前各编辑器选中的标签页
  const [currentLayoutTab, setCurrentLayoutTab] = useState("size");
  const [currentBackgroundTab, setCurrentBackgroundTab] = useState("color");
  const [currentMaskTab, setCurrentMaskTab] = useState("shape");
  const [currentDrawTab, setCurrentDrawTab] = useState("brush");
  const [currentFrameTab, setCurrentFrameTab] = useState("preset");

  /**
   * 处理底部 tab 切换
   */
  const handleTabPress = (newTab: string) => {
    console.log(newTab, "newTab");
    setTab(newTab);

    // 根据不同的tab显示对应的面板
    switch (newTab) {
      case "photo":
        // 直接跳转到图片选择页面
        router.push({
          pathname: "/detail/select-image",
          params: {
            mode: "multiple",
            mediaType: "all",
            maxCount: "10",
            redirectTo: "/detail/free-puzzle",
          },
        });
        break;
      case "layout":
      case "background":
      case "mask":
      case "text":
      case "sticker":
      case "draw":
      case "frame":
        setShowBottomSheet(true);
        break;
      case "canvas":
        // 移除画布功能，导出不是在这里触发
        console.log("画布功能已移除");
        break;
      default:
        console.log(`${newTab} 功能暂未实现`);
    }
  };

  // 获取当前工具栏标题
  const getCurrentToolTitle = () => {
    const currentTab = FREE_PUZZLE_TABS.find((t) => t.key === tab);
    return currentTab ? currentTab.label : "";
  };

  /**
   * 处理底部弹出层取消操作
   */
  const handleBottomSheetCancel = () => {
    setShowBottomSheet(false);
    setShowLayerManager(false);
  };

  /**
   * 处理底部弹出层确认操作
   */
  const handleBottomSheetConfirm = () => {
    // TODO: 实现确认逻辑
    setShowBottomSheet(false);
    setShowLayerManager(false);
  };

  /**
   * 处理上一步操作
   */
  const handlePreviousStep = () => {
    if (canvasRef.current && canvasRef.current.canUndo()) {
      canvasRef.current.undo();
    }
  };

  /**
   * 处理下一步操作
   */
  const handleNextStep = () => {
    if (canvasRef.current && canvasRef.current.canRedo()) {
      canvasRef.current.redo();
    }
  };

  // 处理文字标签页切换
  const handleTextTabChange = (tabKey: string) => {
    setCurrentTextTab(tabKey);
  };

  // 处理文字变化
  const handleTextChange = (textData: any) => {
    console.log("文字数据:", textData);
    setCurrentTextData(textData);
    // 将文字添加到画布
    if (canvasRef.current && textData.text) {
      canvasRef.current.addText(textData);
    }
  };

  /**
   * 处理贴纸选择
   */
  const handleStickerSelect = (sticker: any) => {
    console.log("选中的贴纸:", sticker);
    setCurrentStickerData(sticker);
    // 将贴纸添加到画布
    if (canvasRef.current && sticker.source) {
      // 确保贴纸有正确的数据格式和随机位置
      const stickerData = {
        ...sticker,
        x: Math.random() * 100, // 随机位置
        y: Math.random() * 100,
      };
      canvasRef.current.addSticker(stickerData);
    }
  };

  // 布局相关处理
  const handleSizeSelect = useCallback((size: CanvasSize) => {
    console.log("选择画布尺寸:", size);
    setCanvasSize(size);
    if (canvasRef.current) {
      canvasRef.current.setCanvasSize(size);
    }
    // 更新容器尺寸
    setContainerSize({
      width: size.width,
      height: size.height,
    });
  }, []);

  const handleGridSelect = useCallback((grid: GridLayout) => {
    console.log("选择网格布局:", grid);
    setGridLayout(grid);
    if (canvasRef.current) {
      canvasRef.current.setGridLayout(grid);
    }
  }, []);

  // 照片编辑相关处理
  const handlePhotoEdit = () => {
    console.log("编辑照片");
    // TODO: 跳转到照片编辑页面
  };

  const handlePhotoLayer = () => {
    console.log("照片层级");
    if (selectedLayerId && canvasRef.current) {
      // 显示层级管理
      setShowLayerManager(true);
    }
  };

  const handlePhotoFrame = () => {
    console.log("添加相框");
    // TODO: 实现相框功能
  };

  const handlePhotoBorder = () => {
    console.log("添加边框");
    // TODO: 实现边框功能
  };

  const handlePhotoCopy = () => {
    console.log("复制照片");
    if (selectedLayerId && canvasRef.current) {
      canvasRef.current.copyLayer(selectedLayerId);
    }
  };

  const handlePhotoSetBackground = () => {
    console.log("设为背景");
    // TODO: 实现设为背景功能
  };

  const handlePhotoDelete = () => {
    console.log("删除照片");
    if (selectedLayerId && canvasRef.current) {
      canvasRef.current.deleteLayer(selectedLayerId);
      setSelectedLayerId(undefined);
    }
  };

  // 照片选择器处理
  const handleImageSelect = useCallback(
    (imageData: { source: string; width: number; height: number }) => {
      console.log("选择图片:", imageData);
      if (canvasRef.current) {
        canvasRef.current.addImage(imageData);
      }
      setShowBottomSheet(false);
    },
    []
  );

  const handleVideoSelect = useCallback(
    (videoData: {
      source: string;
      thumbnail: string;
      width: number;
      height: number;
    }) => {
      console.log("选择视频:", videoData);
      if (canvasRef.current) {
        canvasRef.current.addVideo(videoData);
      }
      setShowBottomSheet(false);
    },
    []
  );

  // 背景编辑器处理
  const handleBackgroundColorSelect = (color: string) => {
    console.log("选择背景颜色:", color);
    if (canvasRef.current) {
      canvasRef.current.setBackgroundColor(color);
    }
  };

  const handleBackgroundImageSelect = (imageUri: string) => {
    console.log("选择背景图片:", imageUri);
    if (canvasRef.current) {
      // 设置背景图片
      canvasRef.current.setBackgroundImage(imageUri);
    }
  };

  const handleBackgroundGradientSelect = (gradient: string[]) => {
    console.log("选择背景渐变:", gradient);
    if (canvasRef.current) {
      // 设置渐变背景
      canvasRef.current.setBackgroundGradient(gradient);
    }
  };

  const handleBackgroundPatternSelect = (pattern: string) => {
    console.log("选择背景图案:", pattern);
    if (canvasRef.current) {
      // 设置图案背景
      canvasRef.current.setBackgroundPattern(pattern);
    }
  };

  // 涂鸦工具处理
  const handleBrushSelect = (brush: BrushSettings) => {
    console.log("选择画笔:", brush);
    // 添加涂鸦图层
    if (canvasRef.current) {
      const drawingLayer: Omit<Layer, "id" | "zIndex"> = {
        name: "涂鸦",
        type: "drawing",
        locked: false,
        visible: true,
        data: {
          brushSettings: brush,
          x: 0,
          y: 0,
          width: containerSize.width,
          height: containerSize.height,
          paths: [],
          isDrawing: true,
        },
      };
      canvasRef.current.addLayer(drawingLayer);
    }
  };

  const handleEraserToggle = (enabled: boolean) => {
    console.log("切换橡皮擦:", enabled);
    // 更新涂鸦图层的橡皮擦状态
    if (canvasRef.current) {
      const layers = canvasRef.current.getLayers();
      const drawingLayer = layers.find((l) => l.type === "drawing");
      if (drawingLayer) {
        canvasRef.current.transformLayer(drawingLayer.id, {
          eraserEnabled: enabled,
        });
      }
    }
  };

  const handleClearDrawing = () => {
    console.log("清除涂鸦");
    // 清除涂鸦图层
    if (canvasRef.current) {
      const layers = canvasRef.current.getLayers();
      const drawingLayer = layers.find((l) => l.type === "drawing");
      if (drawingLayer) {
        canvasRef.current.removeLayer(drawingLayer.id);
      }
    }
  };

  // 视频编辑器处理
  const handleVideoTrim = (startTime: number, endTime: number) => {
    console.log("视频裁剪:", startTime, endTime);
    // TODO: 实现视频裁剪
  };

  const handleVideoSpeed = (speed: number) => {
    console.log("视频速度:", speed);
    // TODO: 实现视频速度调整
  };

  const handleVideoVolume = (volume: number) => {
    console.log("视频音量:", volume);
    // TODO: 实现视频音量调整
  };

  // 相框编辑器处理
  const handleFrameSelect = (frame: FrameStyle) => {
    console.log("选择相框:", frame);
    setCurrentFrameData(frame);
    // 应用相框到选中图层
    if (selectedLayerId && canvasRef.current) {
      canvasRef.current.applyFrameToLayer(selectedLayerId, frame);
    }
  };

  const handleFrameCustomize = (settings: FrameSettings) => {
    console.log("自定义相框设置:", settings);
    setCurrentFrameSettings(settings);
    // 应用自定义设置到选中图层
    if (selectedLayerId && canvasRef.current) {
      canvasRef.current.applyFrameSettingsToLayer(selectedLayerId, settings);
    }
  };

  // 蒙版编辑器处理
  const handleMaskSelect = (mask: MaskStyle) => {
    console.log("选择蒙版:", mask);
    setCurrentMaskData(mask);
    // 应用蒙版到选中图层
    if (selectedLayerId && canvasRef.current) {
      canvasRef.current.applyMaskToLayer(selectedLayerId, mask);
    }
  };

  const handleMaskCustomize = (settings: MaskSettings) => {
    console.log("自定义蒙版设置:", settings);
    setCurrentMaskSettings(settings);
    // 应用自定义设置到选中图层
    if (selectedLayerId && canvasRef.current) {
      canvasRef.current.applyMaskSettingsToLayer(selectedLayerId, settings);
    }
  };

  // 画布导出处理
  const handleCanvasExport = (result: any) => {
    console.log("画布导出结果:", result);
    // setShowCanvasExporter(false); // This state was removed, so this line is removed.
  };

  /**
   * 处理画布菜单选择
   */
  const handleCanvasMenuSelect = useCallback(
    (menuType: "photo" | "sticker" | "background" | "text") => {
      console.log("画布菜单选择:", menuType);

      switch (menuType) {
        case "photo":
          // 打开相册选择页面
          router.push({
            pathname: "/detail/select-image",
            params: {
              mode: "multiple",
              mediaType: "all",
              maxCount: "10",
              redirectTo: "/detail/free-puzzle",
            },
          });
          break;
        case "sticker":
          setTab("sticker");
          setShowBottomSheet(true);
          break;
        case "background":
          setTab("background");
          setShowBottomSheet(true);
          break;
        case "text":
          setTab("text");
          setShowBottomSheet(true);
          break;
      }
    },
    [router]
  );

  return (
    <View style={[styles.container, showBottomSheet && styles.containerDark]}>
      <Stack.Screen options={{ headerShown: false }} />
      <View style={[{ paddingTop: insets.top + 4 }]}></View>

      {/* 顶部工具栏 */}
      {!showBottomSheet && !showLayerManager && (
        <View style={[styles.customHeader]}>
          <TouchableOpacity
            style={styles.backButton}
            onPress={() => router.back()}
          >
            <MaterialIcons name="chevron-left" size={24} color="#222" />
          </TouchableOpacity>

          <View style={styles.contentButton}>
            <TouchableOpacity
              style={[
                styles.backButton,
                !canvasRef.current?.canUndo() && styles.disabledButton,
              ]}
              onPress={handlePreviousStep}
              disabled={!canvasRef.current?.canUndo()}
            >
              <SvgIcon
                Icon={retuen}
                size={16}
                color={!canvasRef.current?.canUndo() ? "#ccc" : "#222"}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={[
                styles.backButton,
                { marginLeft: 10 },
                !canvasRef.current?.canRedo() && styles.disabledButton,
              ]}
              onPress={handleNextStep}
              disabled={!canvasRef.current?.canRedo()}
            >
              <SvgIcon
                Icon={goon}
                size={16}
                color={!canvasRef.current?.canRedo() ? "#ccc" : "#222"}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.backButton, { marginLeft: 10 }]}
              onPress={() => {
                console.log("点击图层管理按钮，当前状态:", showLayerManager);
                setShowBottomSheet(false);
                setShowLayerManager(true);
              }}
            >
              <SvgIcon Icon={layers} size={16} color={"#222"} />
            </TouchableOpacity>
          </View>

          <View style={styles.leftButton}>
            <TouchableOpacity style={styles.saveButton}>
              <Text style={styles.saveButtonText}>保存</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.more}>
              <Entypo name="dots-three-vertical" size={12} color="black" />
            </TouchableOpacity>
          </View>
        </View>
      )}

      {/* 画布容器 */}
      <View
        style={[
          styles.canvasContainer,
          showBottomSheet && styles.canvasContainerWithMargin,
        ]}
      >
        <FreePuzzleCanvas
          ref={canvasRef}
          backgroundColor="#FFFFFF"
          disabled={showBottomSheet || showLayerManager}
          canvasWidth={canvasSize.width}
          canvasHeight={canvasSize.height}
          onCanvasMenuSelect={handleCanvasMenuSelect}
        />
      </View>

      {/* 底部工具栏 */}
      {!showBottomSheet && !showLayerManager && (
        <ScrollableToolbar
          tools={FREE_PUZZLE_TABS}
          currentTool={tab}
          onToolPress={handleTabPress}
        />
      )}

      {/* 底部弹出层 */}
      <AnimatedBottomSheet
        visible={showBottomSheet}
        title={getCurrentToolTitle()}
        tabs={
          tab === "text"
            ? TEXT_EDITOR_TABS
            : tab === "layout"
            ? LAYOUT_EDITOR_TABS
            : tab === "background"
            ? BACKGROUND_EDITOR_TABS
            : tab === "mask"
            ? MASK_EDITOR_TABS
            : tab === "draw"
            ? DRAW_TOOL_TABS
            : tab === "frame"
            ? FRAME_EDITOR_TABS
            : undefined
        }
        onTabChange={
          tab === "text"
            ? handleTextTabChange
            : tab === "layout"
            ? setCurrentLayoutTab
            : tab === "background"
            ? setCurrentBackgroundTab
            : tab === "mask"
            ? setCurrentMaskTab
            : tab === "draw"
            ? setCurrentDrawTab
            : tab === "frame"
            ? setCurrentFrameTab
            : undefined
        }
        onCancel={handleBottomSheetCancel}
        onConfirm={handleBottomSheetConfirm}
      >
        {tab === "text" && (
          <TextEditor
            onTextChange={handleTextChange}
            currentTab={currentTextTab}
          />
        )}
        {tab === "sticker" && (
          <StickerEditor onStickerSelect={handleStickerSelect} />
        )}
        {tab === "layout" && (
          <LayoutEditor
            onSizeSelect={handleSizeSelect}
            onGridSelect={handleGridSelect}
            currentTab={currentLayoutTab as "size" | "grid"}
          />
        )}

        {tab === "photo" && selectedLayerId && (
          <PhotoEditor
            onEdit={handlePhotoEdit}
            onLayer={handlePhotoLayer}
            onFrame={handlePhotoFrame}
            onBorder={handlePhotoBorder}
            onCopy={handlePhotoCopy}
            onSetBackground={handlePhotoSetBackground}
            onDelete={handlePhotoDelete}
          />
        )}
        {tab === "background" && (
          <BackgroundEditor
            onColorSelect={handleBackgroundColorSelect}
            onImageSelect={handleBackgroundImageSelect}
            onGradientSelect={handleBackgroundGradientSelect}
            onPatternSelect={handleBackgroundPatternSelect}
            currentTab={
              currentBackgroundTab as "color" | "image" | "gradient" | "pattern"
            }
          />
        )}
        {tab === "mask" && (
          <MaskEditor
            onMaskSelect={handleMaskSelect}
            onMaskCustomize={handleMaskCustomize}
            currentTab={currentMaskTab as "shape" | "gradient"}
          />
        )}
        {tab === "draw" && (
          <DrawingTool
            onBrushSelect={handleBrushSelect}
            onEraserToggle={handleEraserToggle}
            onClearAll={handleClearDrawing}
            currentTab={currentDrawTab as "brush" | "color" | "settings"}
          />
        )}
        {tab === "frame" && (
          <FrameEditor
            onFrameSelect={handleFrameSelect}
            onFrameCustomize={handleFrameCustomize}
            currentTab={currentFrameTab as "preset" | "custom"}
          />
        )}
      </AnimatedBottomSheet>

      {/* 图层管理器 */}
      <LayerManager
        visible={showLayerManager}
        onClose={() => {
          setShowLayerManager(false);
        }}
        getLayers={() => canvasRef.current?.getLayers() || []}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#E4FAF8",
  },
  containerDark: {
    backgroundColor: "#000",
  },
  canvasContainer: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    flexDirection: "row",
  },
  canvasContainerWithMargin: {
    paddingHorizontal: 0,
  },
  customHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: "transparent",
  },
  backButton: {
    width: 30,
    height: 30,
    borderRadius: 20,
    backgroundColor: "rgba(255, 255, 255, 0.9)",
    justifyContent: "center",
    alignItems: "center",
  },
  saveButton: {
    height: 30,
    alignItems: "center",
    justifyContent: "center",
    borderTopLeftRadius: 20,
    borderBottomLeftRadius: 20,
    backgroundColor: "#fff",
    paddingHorizontal: 14,
  },
  saveButtonText: {
    color: "#222",
    fontSize: 12,
    fontWeight: "600",
  },
  contentButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginLeft: 60,
  },
  leftButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  more: {
    height: 30,
    alignItems: "center",
    justifyContent: "center",
    borderTopRightRadius: 20,
    borderBottomRightRadius: 20,
    backgroundColor: "#fff",
    paddingHorizontal: 6,
    marginLeft: 4,
  },
  disabledButton: {
    backgroundColor: "rgba(255, 255, 255, 0.5)",
  },
});
